package com.ysm.smfu.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.ysm.smfu.R;
import com.ysm.smfu.contans.SpKey;
import com.ysm.smfu.protocal.BaseProtocal;
import com.ysm.smfu.protocal.MyStringCallBack;
import com.ysm.smfu.utils.JsonUtil;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.ToastUtils;
import com.ysm.smfu.utils.UIUtils;
import com.ysm.smfu.view.TimeButton;
import com.ysm.smfu.view.XEditText;
import com.ysm.smfu.welcome.SharedConfig;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/9/20.
 */
public class Registe_checkActivity extends BaseActivity {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.et_activity_register_phonenumber)
    XEditText etActivityRegisterPhonenumber;
    @BindView(R.id.et_activity_register_yanzhengma)
    EditText etActivityRegisterYanzhengma;
    @BindView(R.id.btn_activity_register_getyanzhengma)
    TimeButton btnActivityRegisterGetyanzhengma;
    @BindView(R.id.btn_activity_register_register)
    Button btnActivityRegisterRegister;
    @BindView(R.id.register_top_bar_title)
    TextView registopbartitle;

    //    默认验证码
    private String code = "";
    private String num = "";
    private MyReceiver receiver;
    private String zhifupsd;
    private String zhifupsd2;
    private String type;
    private String name;

    //    定义广播接收者，接收广播，关闭页面
    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    }


    @Override
    protected void initViews() {
        super.initViews();
        setContentView(R.layout.activity_register_checkphone);
        ButterKnife.bind(this);
        getConfig();
        zhifupsd = getIntent().getStringExtra(SpKey.INTENT);
        zhifupsd2 = getIntent().getStringExtra(SpKey.INTENT2);
        if (!TextUtils.isEmpty(zhifupsd2) || !TextUtils.isEmpty(zhifupsd)) {
            registopbartitle.setText("修改支付密码");
            btnActivityRegisterRegister.setText("提交");
            type = "password";
        } else {
            btnActivityRegisterRegister.setText("注册");
            registopbartitle.setText("注册");
            type = "register";
        }
        //设置分隔属性
        etActivityRegisterPhonenumber.setPattern(new int[]{3, 4, 4});
        etActivityRegisterPhonenumber.setSeparator(" ");


        etActivityRegisterPhonenumber.setCustomizeMarkerEnable(true);
        etActivityRegisterPhonenumber.setOnMarkerClickListener(new XEditText.OnMarkerClickListener() {
            @Override
            public void onMarkerClick(float x, float y) {
                etActivityRegisterPhonenumber.setText("");
            }
        });

//        注册广播
        IntentFilter intent = new IntentFilter();
        intent.addAction("finishSelf");
        receiver = new MyReceiver();
        registerReceiver(receiver, intent);
    }

    private void getConfig() {
        SharedPreferences sp = new SharedConfig(UIUtils.getContext()).getCommoneSp();
        name = sp.getString(SpKey.NAME, "");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    @OnClick({R.id.btn_activity_register_getyanzhengma, R.id.btn_activity_register_register})
    public void onclick(View view) {
        switch (view.getId()) {
            case R.id.btn_activity_register_getyanzhengma:
                String phoneNumber = etActivityRegisterPhonenumber.getText().toString().trim();
                num = phoneNumber.replace(" ", "");
                if (!num.matches(SpKey.NUMREGEX)) {
                    showErrorDialog("电话号码格式不正确");
//                    不开始倒计时
                    break;
                }
                if (!TextUtils.isEmpty(zhifupsd2) || !TextUtils.isEmpty(zhifupsd)) {
                    if (!TextUtils.equals(num, name)) {
                        showErrorDialog("手机号码必须和登录号码一致");
                        return;
                    }
                }
                if (!btnActivityRegisterGetyanzhengma.isTime())
                    btnActivityRegisterGetyanzhengma.startTime();
                // 获取验证码
                getYzCode();
                break;

            case R.id.btn_activity_register_register:
                if (TextUtils.isEmpty(num)) {
                    showErrorDialog("请先获取验证码");
                    return;
                }
//                对验证码进行验证
                code = etActivityRegisterYanzhengma.getText().toString().trim();
                if (!TextUtils.isEmpty(code))
                    chechYzCode(code);
                else
                    showErrorDialog("验证码为空");
                break;
        }
    }

    /**
     * 错误信息对话框
     */
    private void showErrorDialog(String msg) {
        AlertDialog dialog = new AlertDialog.Builder(this).setMessage(msg)
                .setNegativeButton("确定", null)
                .create();
        dialog.show();
    }

    /**
     * 获取验证码  /user/send
     */
    private void getYzCode() {
        BaseProtocal.builder(true).getYzCode(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("获取验证码" , response);
                //获取验证码之后，验证码输入框获取焦点
                String state = JsonUtil.getState(response);
                if (!TextUtils.equals(state, "1")) {
                    etActivityRegisterYanzhengma.requestFocus();
                    // 如果用户以注册，则停止读秒
                    btnActivityRegisterGetyanzhengma.endTime();
                    showErrorDialog(JsonUtil.getMessage(response));
                    return;
                }
                etActivityRegisterYanzhengma.requestFocus();
            }

            @Override
            public void onFail(Exception e) {
                btnActivityRegisterGetyanzhengma.endTime();
                ToastUtils.showToast("网络超时,请稍后重试");
            }
        }, num, type, zhifupsd, zhifupsd2);
    }

    public void chechYzCode(String code) {
        BaseProtocal.builder(true).checkYzCode(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("检测验证码" ,response);
                String state = JsonUtil.getState(response);
                if (!TextUtils.equals(state, "1")) {
                    showErrorDialog(JsonUtil.getMessage(response));
                    return;
                }
                jumpToNext();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.showToast(getResources().getString(R.string.netError));
            }
        }, num, code, type, zhifupsd, zhifupsd2);
    }

    /**
     * 调到下一步
     */
    private void jumpToNext() {
        if (TextUtils.isEmpty(zhifupsd)) {
//            设置登录密码
            Intent intent = new Intent(UIUtils.getContext(), Registe_setpsdActivity.class);
            intent.putExtra(UIUtils.intentData, num);
            intent.putExtra(UIUtils.intentCode, code);
            startActivity(intent);
            etActivityRegisterYanzhengma.setText("");
        } else if (TextUtils.isEmpty(zhifupsd2)) {
//            修改支付密码
            Intent intent = new Intent(this, ZhiFuPsdActivity.class);
            intent.putExtra(SpKey.INTENT, "intent");
            intent.putExtra(SpKey.CODE, code);
            startActivity(intent);
            finish();
        } else {
//            支付页面的忘记密码，找回密码
            Intent intent = new Intent(this, ZhiFuPsdActivity.class);
//            intent.putExtra("isSet", 1);
//            intent.putExtra(SpKey.INTENT2, "intent2");
            startActivity(intent);
            finish();
        }

        // 设置Activity的切换效果
        overridePendingTransition(R.anim.in_from_right,
                R.anim.out_to_left);
    }
}
